<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <script src="/socket.io/socket.io.js"></script>
    <script src="/js/jquery.js"></script>
    <script src="/babylon.js"></script>
    <script src="/babylonjs.materials.min.js"></script>
    <script src="/babylon.gui.min.js"></script>
    <script src="/pep.min.js"></script>
    <script src="/babylonjs.loaders.min.js"></script>
    <!-- <script src="/js/ammo.js"></script> -->
    <!-- <script src="https://cdnjs.cloudflare.com/ajax/libs/cannon.js/0.6.2/cannon.min.js"></script> -->
    <title>电信Vr游戏大厅</title>
    <style>
        #gdMsglog {
            padding: 0.5em;
            height: 20%;
            width: 40%;
            background: rgba(0, 0, 0, 0.4);
            overflow: scroll;
            overflow-x: hidden;
            overflow-y: auto;
            bottom: 4em;
            left: 2em;
            position: fixed;
            border-top-left-radius: 4px;
            border-top-right-radius: 4px;
        }

        #DivInput {
            padding-right: 0.5em;
            padding-left: 0.5em;
            height: 2em;
            width: 40%;
            background: rgba(0, 0, 0, 0.6);
            border-bottom-left-radius: 4px;
            border-bottom-right-radius: 4px;
            bottom: 2em;
            left: 2em;
            position: fixed;
        }

        #textInput {
            width: 60%;
            height: 2em;
            border-bottom-left-radius: 4px;
            background: rgba(0, 0, 0, 0.6);
            color: white;
        }

        #start,
        #sendText {
            padding-left: 1vw;
            font-size: 0.5rem;
            width: 18%;
            height: 2em;
            border: 0;
            background-color: #448aff21;
            text-decoration: none;
            /*        border-radius: 2px;
*/
            color: #448aff !important;
            color: black;
            background: rgba(1, 1, 1, 0.6);
        }

        html,
        body {
            overflow: hidden;
            width: 100%;
            height: 100%;
            margin: 0;
            padding: 0;
        }

        #renderCanvas {
            width: 100%;
            height: 100%;
            touch-action: none;
            z-index: -1;
        }
    </style>
</head>

<body>
    <!-- <a href="https://www.babylonjs-playground.com/#GM1XMV#3">W3School</a> -->
    <canvas id="renderCanvas"></canvas>
    <!--     <div id="gdMsglog"></div>
    <div id="DivInput">
    <input id="textInput" type="text" >
    <button id="sendText">发送</button>
    <button id="start">长按录音</button> -->
    </div>
    <script>
        window.bg;
        window.logNum = 0;
        window.voiceNum = 0;
        window.userName = 'rdj';
        window.gdMsglog;
        window.sv;
        window.curX;
        window.curZ;
        userName = prompt("请设置你的昵称", "");
        window.socket = io();
        window.voiceArray = new Array();
        window.audio = new Audio();
        window.moveAnimation = null //移动碰撞动画函数
        var human_container=null
        var animationGroups
        var vrHelper
        socket.on('connect', function () {
            socket.emit('join', userName);
            console.log('连接成功')
        });


        socket.on('msg', function (userName, msg) {
            if (typeof (msg[1]) != "undefined")
                if (typeof (msg[1]) != "object") {
                    addMsg(userName, msg[1]);
                }
            else {
                console.log(msg[1]);
                voiceArray[voiceNum] = msg[1];
                addVoice(userName, msg[1]);
            }

        });

        function playVoice(voiceIndex) {
            try {
                audio.pause();
                audio.src = URL.createObjectURL(new Blob(voiceArray[voiceIndex]));
                audio.play();
            } catch (err) {
                alert(err);
            }

        }

        function addhumanInfoUI() {
            // 添加人物信息数据显示框


        }

        socket.on('sys', function (sysMsg, users) {

        });
        let l = console.log
        // const stopButton = document.getElementById('stop');
        // const startButton = document.getElementById('start');
        // const sendTextButton = document.getElementById('sendText');
        // sendTextButton.addEventListener('click', e => {
        //  var input = document.getElementById('textInput');
        //     socket.send(input.value);
        //     input.value="";
        // })


        var canvas = document.getElementById("renderCanvas");
        var engine = new BABYLON.Engine(canvas, true);
        var createScene = function () {
            var scene = new BABYLON.Scene(engine); //场景对象
            var anchor = new BABYLON.TransformNode("");
            vrHelper = scene.createDefaultVRExperience();
            // vrHelper =scene.createDefaultXRExperienceAsync({floorMeshes: [environment.ground]})
            var vrCamera = vrHelper.currentVRCamera
            vrHelper.position.y=50
         
      

            vrHelper.onEnteringVRObservable.add(function () {
           
                vrCamera = vrHelper.currentVRCamera
                //vrHelper.enableInteractions();
            })
            vrHelper.onExitingVRObservable.add(function () {
                vrCamera = vrHelper.currentVRCamera
            })

            scene.onBeforeCameraRenderObservable.add(function(camera) {
                if(human_container){
                    // camera.position.y=5
                    // human_container.parent = camera;
                }
             
            });

            //vrHelper.enableTeleportation({ floorMeshName: "myGround" });
            vrHelper.enableInteractions();

            var gravityVector = new BABYLON.Vector3(0, -9.81, 0);
            // var physicsPlugin = new BABYLON.AmmoJSPlugin;
            scene.collisionsEnabled = true;
            scene.gravity = gravityVector //重力
            // scene.enablePhysics(gravityVector,physicsPlugin);


            var light = new BABYLON.HemisphericLight("light1", new BABYLON.Vector3(0, 1, 0), scene); //平行光灯光对象
            // var camera = new BABYLON.ArcRotateCamera("camera1", Math.PI / 4, Math.PI / 2, 3, new BABYLON.Vector3(0,
            //     20, -20), scene); //环绕相机对象
            // camera.position = new BABYLON.Vector3(0, 10, -20); //环绕相机坐标
            // camera.attachControl(canvas, true);


            var skybox = BABYLON.MeshBuilder.CreateBox("skyBox", {
                size: 1000.0
            }, scene); //天空盒子 （场景）
            var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", scene);
            skyboxMaterial.backFaceCulling = false;
            skyboxMaterial.reflectionTexture = new BABYLON.CubeTexture("textures/skybox", scene);
            skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
            skyboxMaterial.diffuseColor = new BABYLON.Color3(0, 0, 0);
            skyboxMaterial.specularColor = new BABYLON.Color3(0, 0, 0);
            skybox.material = skyboxMaterial;
            skybox.position = new BABYLON.Vector3(0, 0, 0); //天空盒子位置
            skybox.checkCollisions = false
            var ground = BABYLON.MeshBuilder.CreateGround("myGround", { //地板
                width: 1000,
                height: 1000
            }, scene);

            var materialSphere1 = new BABYLON.StandardMaterial("textures1", scene);
            materialSphere1.ambientTexture = new BABYLON.Texture("textures/wall3.jpg", scene); //地板纹理图片
            materialSphere1.ambientTexture.uSale = 50
            materialSphere1.ambientTexture.vScale = 50
            materialSphere1.alpha = 0; //地板透明度
            ground.material = materialSphere1;

            ground.checkCollisions = true;


            var assetsManager = new BABYLON.AssetsManager(scene);
            var sceneMeshTask = assetsManager.addMeshTask("scene", "", "scenes/", "电信VR大厅2.2.babylon");
            arcadeGameLoder(assetsManager)
            var humanMeshTask = assetsManager.addMeshTask("human", "", "mesh/boy_3d/", "boy.gltf");
            // console.log(meshTask);
            var containerMaterial = new BABYLON.StandardMaterial("containerMaterial", scene); // 容器材质
            containerMaterial.diffuseColor = new BABYLON.Color3(1, 1, 1);
            containerMaterial.alpha = 0;


            human_container = BABYLON.MeshBuilder.CreateBox('human_container', {
                width: 5,
                height: 10,
                depth: 5
            }, scene) //人物模型容器
            var human = new BABYLON.Mesh('humanBoy') //人物模型
            var humanAnimation = null //人物骨骼
            var myscene = null //场景模型

            human_container.position = new BABYLON.Vector3(0, 5, 0)
            human_container.material = containerMaterial
            var humanInfoPannel = BABYLON.MeshBuilder.CreatePlane("humanInfoPannel", {
                width: 6,
                height: 6 / 4
            }) //人类信息模板
            humanInfoPannel.position = new BABYLON.Vector3(0, 10, 0)
            human_container.addChild(humanInfoPannel)

            var toolsViewPannel = BABYLON.MeshBuilder.CreatePlane("toolsView", {
                width: 3,
                height: 2
            }) // 工具信息栏
            toolsViewPannel.position = new BABYLON.Vector3(-5, 5, 0)
            human_container.addChild(toolsViewPannel)

            var HumanMsgManager = createHumanMsgManager(humanInfoPannel)
            var toolsViewManager = createtoolsViewManager(toolsViewPannel)
            console.log('工具栏', toolsViewManager)

            addHumanMsg(window.userName, HumanMsgManager)
            addToolsViewUI(toolsViewManager)
            var chatView = addChatViewUI()
            human_container.addChild(chatView)

            scene.registerBeforeRender(function () {
          
                // vrCamera = vrHelper.currentVRCamera
                // console.log('相机',vrHelper)
                // vrHelper.position = new BABYLON.Vector3(human_container.position.x, human_container.position
                //     .y + 30, human_container.position.z - 20) //vrhelp 内置相机坐标
                // vrCamera.lockedTarget = human_container;
                // chatView.rotation = new BABYLON.Vector3(0 - chatView.parent.rotation.x +
                //     vrCamera.rotation.x, 0 - chatView.parent.rotation.y +
                //     vrCamera.rotation.y, 0 - chatView.parent.rotation.z +
                //     vrCamera.rotation.z);
                // humanInfoPannel.rotation = new BABYLON.Vector3(0 - humanInfoPannel.parent.rotation.x +
                //     vrCamera.rotation.x, 0 - humanInfoPannel.parent.rotation.y +
                //     vrCamera.rotation.y, 0 - humanInfoPannel.parent.rotation.z +
                //     vrCamera.rotation.z); // 计算人物信息面朝相机角度

                // toolsViewPannel.rotation = new BABYLON.Vector3(0 - toolsViewPannel.parent.rotation.x +
                //     vrCamera.rotation.x, 0 - toolsViewPannel.parent.rotation.y +
                //     vrCamera.rotation.y, 0 - toolsViewPannel.parent.rotation.z +
                //     vrCamera.rotation.z); // 计算工具面板面朝相机角度

                // console.log('工具面板', toolsViewPannel)

            });


            sceneMeshTask.onSuccess = function (task) {
                // vrHelper.enableTeleportation({ floorMeshName: "myGround" });
                //vrHelper.enableInteractions();
                console.log('场景', task);
                // task.loadedMeshes[2].position = BABYLON.Vector3.Zero();
                // task.loadedMeshes.scaling.scaleInPlace(1)
                task.loadedMeshes.forEach(function (mesh, index) {
                    mesh.checkCollisions = true
                    myscene = mesh
                    myscene.scaling.scaleInPlace(0.5)
                    myscene.position = new BABYLON.Vector3(0, 50, 0)
                    // myscene.physicsImpostor = new BABYLON.PhysicsImpostor(myscene, BABYLON.PhysicsImpostor.MeshImpostor, {mass: 0, friction: 0, restitution: 0});


                    // mesh.rotation = new BABYLON.Vector3(Math.PI * 1.5, 0, 0);
                });


            }
            sceneMeshTask.onError = function (task, message, exception) {
                console.log(message, exception);
            }

            humanMeshTask.onSuccess = function (task) {
                console.log('人物', task);
                // task.loadedMeshes[2].position = BABYLON.Vector3.Zero();
                // task.loadedMeshes.scaling.scaleInPlace(1)
                animationGroups = task.loadedAnimationGroups[0]
                animationGroups.stop()
                animationGroups.start(true, 1, 2.4, 10.6) //站立待机动画

                console.log('人物动画', humanAnimation)
                // scene.beginAnimation(humanAnimation, 126, 316, false, 1.0);
                task.loadedMeshes.forEach(function (mesh, index) {
                    mesh.scaling.scaleInPlace(0.004);
                    human.addChild(mesh)
                    // mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, BABYLON.PhysicsImpostor.MeshImpostor, {mass: 1});

                    // mesh.rotation = new BABYLON.Vector3(Math.PI * 1.5, 0, 0);
                });
                human_container.addChild(human)
                human_container.checkCollisions = false
                // // human_container.physicsImpostor = new BABYLON.PhysicsImpostor(human_container, BABYLON.PhysicsImpostor.BoxImpostor, {mass: 1, friction: 1,restitution: 1});
                // human_container.ellipsoid = new BABYLON.Vector3(10, 1, 5);
                // human_container.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
                // human_container.applyGravity = true;

                console.log('资源', task)
            

                console.log("success");
            }
            humanMeshTask.onError = function (task, message, exception) {
                console.log(message, exception);
            }

            assetsManager.load();
            BABYLON.SceneLoader.Append("scenes/", "1.gltf", scene, function (scene) {
                // do something with the scene
            });
            scene.onPointerDown = function (evt, pickResult) {
             
                console.log('点击结果', pickResult);
                if (pickResult.pickedMesh.id === 'myGround') {
                    // scene.beginAnimation(humanAnimation, 0, 45, true, 1.0);
                    console.log('vr相机',vrCamera)
                    animationGroups.stop()
                    animationGroups.start(true, 1, 1.6, 2.3) //走路动画
                    curX = pickResult.pickedPoint.x;
                    curZ = pickResult.pickedPoint.z;
                    var frameRate = 60; //帧率
                    var targetposition = new BABYLON.Vector3(curX, vrHelper.position.y, curZ) //移动目标位置
                    var x = pickResult.pickedPoint.x - vrHelper.position.x;
                    var y = pickResult.pickedPoint.z - vrHelper.position.z;
                    var destination = Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2)); //距离

                    var cos = y / destination;
                    var sin = x / destination;
                    var radina = Math.acos(cos);
                    var radina2 = Math.asin(sin);
                    if (x < 0) {
                        if (y > 0) {
                            radina = radina2;
                        } else {
                            radina = Math.acos(-cos) + Math.PI;
                        }
                    }


                    human.rotation.y = radina;

                    //Position Animation
                    // var Move = new BABYLON.Animation("move", "position", frameRate, BABYLON.Animation
                    //     .ANIMATIONTYPE_VECTOR3);

                    // console.log('距离', destination)

                    human_container.onCollideObservable.add(function () {
                        console.log('碰撞')
                        scene.onBeforeRenderObservable.remove(window.moveAnimation)
                    })

                    // BABYLON.Animation.TransitionTo('position', targetposition, vrCamera, scene,
                    //     frameRate, Move, destination * 50) //动画移动

                    /*碰撞移动*/
                    // console.log(window.moveAnimation)
                    if (window.moveAnimation) {
                        console.log('清除')
                        scene.onBeforeRenderObservable.remove(window.moveAnimation)
                    }

                    // var positionOriginX = vrHelper.position.x //移动模型源位置x
                    // var positionOriginZ = vrHelper.position.z //移动模型源位置z

                    window.moveAnimation = scene.onBeforeRenderObservable.add(() => {
                        var velocity = 0.15 //速度 0-1 z轴速度
                        // curX = pickResult.pickedPoint.x; //x目的点位置
                        // curZ = pickResult.pickedPoint.z; //z目的点位置
                        var positionX = vrHelper.position.x //移动模型当前位置x
                        var positionZ = vrHelper.position.z //移动模型当前位置z
                        // var distanceRate = Math.abs(curX - positionOriginX / curZ - positionOriginZ) // 两点间距离比 有很大误差
                        var backwards = new BABYLON.Vector3(0, vrHelper.position.y, 0);
                        // console.log('点', Math.round(positionX * 1),Math.round(curX * 1))

                        if (Math.round(positionX * 1) === Math.round(curX * 1) && Math.round(positionZ *
                                1) === Math.round(curZ * 1)) {
                            // 不保留小数4舍5入 判断是否到达终点
                            animationGroups.stop()
                            animationGroups.start(true, 1, 2.4, 10.6) //站立待机动画
                            console.log('终点')
                            scene.onBeforeRenderObservable.remove(window.moveAnimation)

                        } else if (Math.round(positionX * 1) === Math.round(curX * 1)) {
                            // 不保留小数4舍5入 判断x轴是否到达终点

                            if (positionZ < curZ) {
                                // var backwards = new BABYLON.Vector3( backwards.x ,  backwards.y, backwards.z+ 0.05);
                                // vrCamera.moveWithCollisions(backwards);
                                positionZ += velocity
                                backwards.z = velocity
                                // console.log('移动3')
                            }
                            if (positionZ > curZ) {
                                // var backwards = new BABYLON.Vector3( backwards.x ,  backwards.y, backwards.z- 0.05);
                                // vrCamera.moveWithCollisions(backwards);
                                positionZ -= velocity
                                backwards.z = -velocity
                                // console.log('移动4')
                            }


                        } else if (Math.round(positionZ * 1) === Math.round(curZ * 1)) {
                            if (positionX < curX) {

                                positionX += velocity
                                backwards.x = velocity
                                // console.log('移动1')
                            }
                            if (positionX > curX) {
                                // var backwards = new BABYLON.Vector3( backwards.x - 0.05,  backwards.y, backwards.z);
                                // vrCamera.moveWithCollisions(backwards);
                                positionX -= velocity
                                backwards.x = -velocity
                                // console.log('移动2')
                            }
                        } else {


                            if (positionX < curX) {

                                positionX += velocity
                                backwards.x = velocity
                                // console.log('移动1')
                            }
                            if (positionX > curX) {
                                // var backwards = new BABYLON.Vector3( backwards.x - 0.05,  backwards.y, backwards.z);
                                // vrCamera.moveWithCollisions(backwards);
                                positionX -= velocity
                                backwards.x = -velocity
                                // console.log('移动2')
                            }
                            if (positionZ < curZ) {
                                // var backwards = new BABYLON.Vector3( backwards.x ,  backwards.y, backwards.z+ 0.05);
                                // vrCamera.moveWithCollisions(backwards);
                                positionZ += velocity
                                backwards.z = velocity
                                // console.log('移动3')
                            }
                            if (positionZ > curZ) {
                                // var backwards = new BABYLON.Vector3( backwards.x ,  backwards.y, backwards.z- 0.05);
                                // vrCamera.moveWithCollisions(backwards);
                                positionZ -= velocity
                                backwards.z = -velocity
                                // console.log('移动4')
                            }

                        }

                        // vrHelper.position.negate();
                    
                        vrHelper.position=new BABYLON.Vector3(positionX,vrHelper.position,y,positionZ);

                        console.log('移动', vrHelper.position)
                    });


                }

            }
            return scene;
        }
        var scene = createScene();
        engine.runRenderLoop(function () {
            scene.render();
        });
        window.addEventListener("resize", function () {
            engine.resize();
        });

        function arcadeGameLoder(assetsManager) {
            // 加载街机
            var tuiXiangZiTask = assetsManager.addMeshTask("街机-推箱子", "", "mesh/arcadeGame/", "tuixiangzi.babylon");
            var wuZiQiTask = assetsManager.addMeshTask("街机-五子棋", "", "mesh/arcadeGame/", "wuziqi.babylon");
            var VrShiPingTask = assetsManager.addMeshTask("街机-VR视频", "", "mesh/arcadeGame/", "vrshiping.babylon");
            tuiXiangZiTask.onSuccess = function (task) {
                console.log('街机', task);
                // task.loadedMeshes[2].position = BABYLON.Vector3.Zero();
                // task.loadedMeshes.scaling.scaleInPlace(1)
                var arcadeGame = null
                task.loadedMeshes.forEach(function (mesh, index) {

                    arcadeGame = mesh
                    arcadeGame.position = new BABYLON.Vector3(70, 8.5, 100)
                    arcadeGame.scaling.scaleInPlace(0.05);
                    arcadeGame.checkCollisions = true
                    // arcadeGame.physicsImpostor = new BABYLON.PhysicsImpostor(arcadeGame, BABYLON.PhysicsImpostor.BoxImpostor, {mass: 1, friction: 1,restitution: 1});
                    arcadeGame.ellipsoid = new BABYLON.Vector3(1, 1, 1);
                    arcadeGame.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
                    arcadeGame.applyGravity = true;
                    // mesh.rotation = new BABYLON.Vector3(Math.PI * 1.5, 0, 0);
                });

            }
            tuiXiangZiTask.onError = function (task, message, exception) {
                console.log(message, exception);
            }

            wuZiQiTask.onSuccess = function (task) {
                // console.log(task);
                // task.loadedMeshes[2].position = BABYLON.Vector3.Zero();
                // task.loadedMeshes.scaling.scaleInPlace(1)
                var arcadeGame = null
                task.loadedMeshes.forEach(function (mesh, index) {
                    arcadeGame = mesh
                    arcadeGame.position = new BABYLON.Vector3(40, 8.5, 100)
                    arcadeGame.scaling.scaleInPlace(0.05);
                    arcadeGame.checkCollisions = true
                    // arcadeGame.physicsImpostor = new BABYLON.PhysicsImpostor(arcadeGame, BABYLON.PhysicsImpostor.BoxImpostor, {mass: 1, friction: 1,restitution: 1});
                    arcadeGame.ellipsoid = new BABYLON.Vector3(1, 1, 1);
                    arcadeGame.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
                    arcadeGame.applyGravity = true;
                    // mesh.rotation = new BABYLON.Vector3(Math.PI * 1.5, 0, 0);
                });

            }
            wuZiQiTask.onError = function (task, message, exception) {
                console.log(message, exception);
            }

            VrShiPingTask.onSuccess = function (task) {
                // console.log(task);
                // task.loadedMeshes[2].position = BABYLON.Vector3.Zero();
                // task.loadedMeshes.scaling.scaleInPlace(1)
                var arcadeGame = null
                task.loadedMeshes.forEach(function (mesh, index) {
                    arcadeGame = mesh
                    arcadeGame.position = new BABYLON.Vector3(55, 8.5, 100)
                    arcadeGame.scaling.scaleInPlace(0.05);
                    arcadeGame.checkCollisions = true
                    // arcadeGame.physicsImpostor = new BABYLON.PhysicsImpostor(arcadeGame, BABYLON.PhysicsImpostor.BoxImpostor, {mass: 1, friction: 1,restitution: 1});
                    arcadeGame.ellipsoid = new BABYLON.Vector3(1, 1, 1);
                    arcadeGame.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
                    arcadeGame.applyGravity = true;
                    // mesh.rotation = new BABYLON.Vector3(Math.PI * 1.5, 0, 0);
                });

            }
            VrShiPingTask.onError = function (task, message, exception) {
                console.log(message, exception);
            }



        }

        function createHumanMsgManager(mesh) {
            // 创建人类信息UI管理者
            var manager = new BABYLON.GUI.AdvancedDynamicTexture.CreateForMesh(mesh,
                1024,
                1024 / 4
            );
            // Create a horizontal stack panel
            return manager
        }

        function addHumanMsg(userName, manager) {
            // 添加人类信息 
            var panel = new BABYLON.GUI.StackPanel();
            panel.margin = 0.02;
            manager.addControl(panel);

            var nameView = new BABYLON.GUI.Rectangle();
            nameView.width = '1000px';
            nameView.height = "200px";
            nameView.cornerRadius = 100;
            nameView.color = "Orange";
            nameView.thickness = 20;
            nameView.background = "black";
            nameView.alpha = 0.7
            panel.addControl(nameView);


            var nameText = new BABYLON.GUI.TextBlock();
            nameText.textWrapping = BABYLON.GUI.TextWrapping.WordWrap;
            nameText.paddingTop = "10px";
            nameText.paddingLeft = "100px";
            nameText.paddingRight = "100px";
            nameText.paddingBottom = "10px";
            nameText.fontSize = "100px";
            nameText.horizontalAlignment = BABYLON.GUI.Control.HORIZONTAL_ALIGNMENT_LEFT;
            nameText.verticalAlignment = BABYLON.GUI.Control.VERTICAL_ALIGNMENT_TOP;
            nameText.textHorizontalAlignment = BABYLON.GUI.Control.HORIZONTAL_ALIGNMENT_LEFT;
            nameText.textVerticalAlignment = BABYLON.GUI.Control.VERTICAL_ALIGNMENT_TOP;
            nameText.color = "white";
            nameText.text = userName;
            nameText.resizeToFit = true;

            nameView.addControl(nameText);



            return panel

        }


        function createtoolsViewManager(mesh) {
            // 创建人类信息UI管理者
            var manager = new BABYLON.GUI.AdvancedDynamicTexture.CreateForMesh(mesh, 1024, 1024);
            // Create a horizontal stack panel
            return manager
        }

        function addToolsViewUI(manager) {
            // 添加工具窗口 
            var panel = new BABYLON.GUI.StackPanel();
            // panel.margin = 0.02;
            panel.width = '1000px';
            panel.height = '1000px';
            panel.verticalAlignment = BABYLON.GUI.Control.VERTICAL_ALIGNMENT_TOP
            manager.addControl(panel);



            var openChat = addToolsButtonUI('聊天') //打开聊天按钮
            var sayHello = addToolsButtonUI('打招呼') //打招呼按钮

            panel.addControl(openChat);
            panel.addControl(sayHello);

            openChat.onPointerClickObservable.add(() => {
                console.log('打开聊天室')
            })

            sayHello.onPointerClickObservable.add(() => {
                console.log('打招呼')
            })



            return panel

        }

        function addToolsButtonUI(name) {
            // 添加工具按钮
            var button = new BABYLON.GUI.Button;
            button.width = '1000px';
            button.height = '500px';
            button.background = "black";
            button.alpha = 0.7

            var Text = new BABYLON.GUI.TextBlock();
            Text.textWrapping = BABYLON.GUI.TextWrapping.WordWrap;

            Text.fontSize = '250px'
            Text.paddingTop = "100px";
            Text.paddingLeft = "100px";
            Text.paddingRight = "100px";
            Text.paddingBottom = "100px";
            Text.horizontalAlignment = BABYLON.GUI.Control.HORIZONTAL_ALIGNMENT_LEFT;
            Text.verticalAlignment = BABYLON.GUI.Control.VERTICAL_ALIGNMENT_TOP;
            Text.textHorizontalAlignment = BABYLON.GUI.Control.HORIZONTAL_ALIGNMENT_LEFT;
            Text.textVerticalAlignment = BABYLON.GUI.Control.VERTICAL_ALIGNMENT_TOP;
            Text.color = "white";
            Text.text = name;
            Text.resizeToFit = true;

            button.addControl(Text);
            return button
        }


        function addChatViewUI() {
            // 添加聊天室语音

            var plane = BABYLON.MeshBuilder.CreatePlane("plane", {
                width: 14,
                height: 14 / 2
            });

            plane.outlineColor = new BABYLON.Color3(1, 1, 0)
            plane.outlineWidth = 10
            plane.position.set(10, 5, 0);
            // plane.position = vrHelper.webVRCamera.getFrontPosition;
            var advancedTexture = BABYLON.GUI.AdvancedDynamicTexture.CreateForMesh(plane, 1024, 1024 / 2);

            var gd = new BABYLON.GUI.Grid();
            gd.width = 1;
            gd.height = 1;
            gd.addRowDefinition(4 / 5);
            gd.addRowDefinition(1 / 5);
            gd.horizontalAlignment = BABYLON.GUI.Control.HORIZONTAL_ALIGNMENT_CENTER;
            gd.verticalAlignment = BABYLON.GUI.Control.VERTICAL_ALIGNMENT_BOTTOM;
            // gd.background = "black";
            gd.paddingLeft = "2%";
            gd.paddingBottom = "10%";
            // gd.alph  a=0.4;
            advancedTexture.addControl(gd);
            sv = new BABYLON.GUI.ScrollViewer("sv");
            sv.width = 1;
            sv.height = 1;
            gd.addControl(sv, 0, 0);
            console.log('网格', gd)

            var gdInput = new BABYLON.GUI.Grid("gd");
            gdInput.width = 1;
            gdInput.height = 1;
            gdInput.background = "black";
            gdInput.alpha = 0.7;
            gdInput.addColumnDefinition(3 / 5);
            gdInput.addColumnDefinition(1 / 5);
            gdInput.addColumnDefinition(1 / 5);
            gd.addControl(gdInput, 1, 0);

            var inputText = new BABYLON.GUI.InputText("inputtext");
            inputText.width = 1;
            inputText.height = 1;
            inputText.color = "white";
            inputText.fontSize = '40px'
            gdInput.addControl(inputText, 0, 0);
            var sendBtn = BABYLON.GUI.Button.CreateSimpleButton("sendBtn", "发送");
            sendBtn.width = 1;
            sendBtn.height = 1;
            sendBtn.color = "white"
            sendBtn.fontSize = '40px'
            gdInput.addControl(sendBtn, 0, 1);
            var voiceBtn = BABYLON.GUI.Button.CreateSimpleButton("voiceBtn", "按下录音");
            voiceBtn.width = 1;
            voiceBtn.height = 1;
            voiceBtn.color = "white"
            voiceBtn.fontSize = '40px'
            gdInput.addControl(voiceBtn, 0, 2);

            sendBtn.onPointerClickObservable.add(() => {
                var textMsg = [];
                var type = "home";
                textMsg.push(type);
                textMsg.push(inputText.text);
                socket.send(textMsg);
                inputText.text = "";
            })

            navigator.mediaDevices.getUserMedia({
                    audio: true,
                    // video: true
                })
                .then(stream => {
                    voiceBtn.onPointerUpObservable.add(() => {
                        mediaRecorder.stop();
                        voiceBtn.textBlock.text = '长按录音';
                    })

                    voiceBtn.onPointerDownObservable.add(() => {
                        mediaRecorder.start();
                        voiceBtn.textBlock.text = '松开发送';
                    })
                    var recordedChunks = [];

                    const mediaRecorder = new MediaRecorder(stream);
                    mediaRecorder.addEventListener('dataavailable', function (e) {
                        recordedChunks = [];
                        if (e.data.size > 0) {
                            recordedChunks.push(e.data);
                        }
                    });

                    mediaRecorder.addEventListener('stop', function () {
                        l('暂停')
                        var data = ["home", recordedChunks];
                        socket.send(data);
                    });

                    mediaRecorder.addEventListener('start', e => {
                        l('开始')
                    })
                });

            // bg = new BABYLON.GUI.Container('bg');
            bg = new BABYLON.GUI.Container('bgcolor');
            bg.background = "black";
            bg.alpha = 0.7;
            // bg.width=1;
            // bg.height=1;
            sv.addControl(bg);
            gdMsglog = new BABYLON.GUI.Grid();
            console.log('背景高度', bg.heightInPixels)
            gdMsglog.heightInPixels = bg.heightInPixels;
            sv.addControl(gdMsglog);

            return plane
        }


        function addMsg(userName, msg) {
            var gdText = new BABYLON.GUI.Grid();

            gdText.addColumnDefinition(85, true);
            gdText.addColumnDefinition(200, true);
            gdText.adaptHeightToChildren = true;
            gdText.height = "90px"
            var tb = new BABYLON.GUI.TextBlock();
            tb.textWrapping = BABYLON.GUI.TextWrapping.WordWrap;
            tb.paddingTop = "20px";
            tb.paddingLeft = "10px";
            // tb.paddingRight = "10px";
            tb.paddingBottom = "20px";
            // tb.height="40px";
            tb.horizontalAlignment = BABYLON.GUI.Control.HORIZONTAL_ALIGNMENT_LEFT;
            tb.verticalAlignment = BABYLON.GUI.Control.VERTICAL_ALIGNMENT_TOP;
            tb.textHorizontalAlignment = BABYLON.GUI.Control.HORIZONTAL_ALIGNMENT_LEFT;
            tb.textVerticalAlignment = BABYLON.GUI.Control.VERTICAL_ALIGNMENT_TOP;
            tb.color = "white";
            tb.fontSize = "40px";
            tb.text = userName + ":";
            tb.resizeToFit = true;
            gdText.addControl(tb, 0, 0);
            var tbMsg = new BABYLON.GUI.TextBlock();
            tbMsg.textWrapping = BABYLON.GUI.TextWrapping.WordWrap;
            tbMsg.paddingTop = "20px";
            tbMsg.paddingLeft = "20px";
            // tbMsg.paddingRight = "10px";
            tbMsg.paddingBottom = "20px";
            tbMsg.fontSize = "40px";
            tbMsg.horizontalAlignment = BABYLON.GUI.Control.HORIZONTAL_ALIGNMENT_LEFT;
            tbMsg.verticalAlignment = BABYLON.GUI.Control.VERTICAL_ALIGNMENT_TOP;
            tbMsg.textHorizontalAlignment = BABYLON.GUI.Control.HORIZONTAL_ALIGNMENT_LEFT;
            tbMsg.textVerticalAlignment = BABYLON.GUI.Control.VERTICAL_ALIGNMENT_TOP;
            tbMsg.color = "white";
            // tbMsg.height="40px";
            tbMsg.text = msg;
            gdText.addControl(tbMsg, 0, 1);
            gdMsglog.addRowDefinition(40, true);
            gdMsglog.addControl(gdText, logNum + voiceNum, 0);
            console.log(bg.heightInPixels);
            gdMsglog.height = (logNum + 1) * 40 + (voiceNum + 1) * 40 + "px";
            if (bg.heightInPixels < ((logNum + 1) * 40 + (voiceNum + 1) * 40)) {
                bg.height = (logNum + 1) * 40 + (voiceNum + 1) * 40 + "px";
            }
            sv.verticalBar.value = 1;
            logNum++;
        }

        function addVoice(userName, msg) {
            var gdVoice = new BABYLON.GUI.Grid();
            gdVoice.addColumnDefinition(65, true);
            gdVoice.addColumnDefinition(200, true);
            var tb = new BABYLON.GUI.TextBlock();
            tb.textWrapping = BABYLON.GUI.TextWrapping.WordWrap;
            tb.resizeToFit = true;
            tb.paddingTop = "10px";
            tb.paddingLeft = "10px";
            tb.paddingRight = "10px";
            tb.horizontalAlignment = BABYLON.GUI.Control.HORIZONTAL_ALIGNMENT_LEFT;
            tb.verticalAlignment = BABYLON.GUI.Control.VERTICAL_ALIGNMENT_TOP;
            tb.textHorizontalAlignment = BABYLON.GUI.Control.HORIZONTAL_ALIGNMENT_LEFT;
            tb.textVerticalAlignment = BABYLON.GUI.Control.VERTICAL_ALIGNMENT_TOP;
            tb.color = "white";
            tb.text = userName + ":";
            gdVoice.addControl(tb, 0, 0);
            var imgVoice = BABYLON.GUI.Button.CreateImageOnlyButton(voiceNum, "textures/yyt.png");

            // var imgVoice = new BABYLON.GUI.Image(voiceNum, "textures/yyt.png");
            imgVoice.width = "200px";
            imgVoice.height = "30px";
            imgVoice.color = "transparent";
            imgVoice.onPointerClickObservable.add(() => {
                playVoice(imgVoice.name);
                l(imgVoice.name);
            })
            gdVoice.addControl(imgVoice, 0, 1);
            gdMsglog.addRowDefinition(40, true);
            gdMsglog.addControl(gdVoice, logNum + voiceNum, 0);
            console.log(gdMsglog.heightInPixels);
            gdMsglog.height = (logNum + 1) * 40 + (voiceNum + 1) * 40 + "px";
            if (bg.heightInPixels < ((logNum + 1) * 40 + (voiceNum + 1) * 40)) {
                bg.height = (logNum + 1) * 40 + (voiceNum + 1) * 40 + "px";
            }
            sv.verticalBar.value = 1;
            voiceNum++;
        }
    </script>
</body>

</html>